<template>
  <div>
    <div
      style="padding-top: 30px"
      v-if="showSearch"
      :class="{
        'enter-level flipInX': showSearch,
      }"
    >
      <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
        <el-form-item label="商品名称">
          <el-input
            v-model="searchFrom.name"
            placeholder="请输入商品名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="商品折扣">
          <el-input
            v-model.number="searchFrom.discount"
            placeholder="请输入商品折扣"
            clearable
          />
        </el-form-item>

        <el-form-item label="类型">
          <el-select
            v-model="searchFrom.marketable"
            placeholder="类型"
            clearable
          >
            <el-option label="上架" value="1" />
            <el-option label="下架" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">
            搜索
          </el-button>
          <el-button type="info" @click="reset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 30px">
      <div
        style="
          padding-bottom: 20px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>
          <el-button :icon="Plus" type="success" @click="insertOne">
            新增
          </el-button>
          <el-popconfirm
            title="确定删除吗？"
            @confirm="batchDel"
            @cancel="cancelEvent"
          >
            <template #reference>
              <el-button type="danger" :icon="Delete" :disabled="isBatch">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </div>
        <div>
          <el-button :icon="Search" circle @click="isShowSearch"></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        style="width: 100%"
        :height="tableHeight"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column
          type="index"
          :index="indexMethod"
          label="编号"
          width="105"
          fixed
        />
        <el-table-column property="title" label="商品名称" width="200" />
        <el-table-column
          property="desc"
          label="商品描述"
          width="300"
          show-overflow-tooltip
        />
        <el-table-column label="商品图" width="300">
          <template #default="scope">
            <el-image
              style="width: 100px; height: 60px"
              :src="scope.row.imgUrl"
              fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column property="price" label="价格" width="200" sortable />
        <el-table-column
          property="discount"
          label="折扣"
          width="150"
          sortable
        />
        <el-table-column property="sort" label="排序" width="200" sortable />
        <el-table-column label="状态" width="130">
          <template #default="scope">
            <el-tag
              :type="scope.row.marketable === 1 ? 'success' : 'error'"
              disable-transitions
            >
              {{ scope.row.marketable === 1 ? "已上架" : "已下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品类型" width="130">
          <template #default="scope">
            {{ scope.row.type === 1 ? "会员商品" : "其他商品" }}
          </template>
        </el-table-column>
        <el-table-column property="buyCount" label="购买人数" width="150" />
        <el-table-column label="创建时间" width="200">
          <template #default="scope">{{
            tool.formatDateToYYYYMMDD(scope.row.createTime)
          }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button @click="oper(scope.row, 1)" type="text" :icon="EditPen">
              修改
            </el-button>
            <el-button
              @click="oper(scope.row.id, 3)"
              type="text"
              :icon="Download"
              v-if="scope.row.marketable === 1"
            >
              下架
            </el-button>
            <el-button
              @click="oper(scope.row.id, 3)"
              type="text"
              :icon="Upload"
              v-else
            >
              上架
            </el-button>
            <el-popconfirm
              title="确定删除吗？"
              @confirm="oper(scope.row.id, 2)"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button type="text" :icon="Delete"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-pagination
          :hide-on-single-page="true"
          background
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.size"
          :page-count="page.pages"
          @current-change="changePage"
          :pager-count="15"
        />
      </div>
    </div>
  </div>
  <add-shop
    @upload="onUpload"
    ref="addDataRef"
    @common="handlerCommon"
  ></add-shop>
</template>

<script setup>
import request from "@/assets/js/request";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import addShop from "@/components/shop/add-shop.vue";
import tool from "@/assets/js/tool";
import {
  Search,
  Refresh,
  EditPen,
  Delete,
  Download,
  Upload,
  Plus,
} from "@element-plus/icons-vue";
import axios from "axios";

const showSearch = ref(true);
const searchFrom = ref({
  name: "",
  discount: null,
  pageSize: 20,
  pageNum: 1,
  marketable: null,
});

const loading = ref(false);

const addDataRef = ref();
const selectable = ref();
const dataList = ref([]);
const isBatch = ref(true);
const tableHeight = ref(600);
const selectData = ref([]);
const imgUrl = ref("");
const isSend = ref(0);
const page = ref({
  size: 20,
  num: 1,
  pages: 1,
  total: 0,
});

const indexMethod = (index) => {
  return index + 1;
};

const isShowSearch = () => {
  showSearch.value = !showSearch.value;
  if (showSearch.value) {
    tableHeight.value = 600;
  } else {
    tableHeight.value = 700;
  }
};
//获取数据
const getDataList = () => {
  loading.value = true;
  searchFrom.value.pageNum = page.value.num;
  searchFrom.value.pageSize = page.value.size;
  request
    .post(`/shop/page`, searchFrom.value)
    .then((res) => {
      if (res.code === 200) {
        dataList.value = res.data.records;
        page.value.num = res.data.current;
        page.value.pages = res.data.pages;
        page.value.total = res.data.total;
      } else {
        ElMessage.error(res.msg);
      }
      loading.value = false;
    })
    .catch((err) => {
      ElMessage.error(err);
    });

  setTimeout(() => {
    loading.value = false;
  }, 5000);
};

const changePage = (pageIndex) => {
  console.log(pageIndex);
  page.value.num = pageIndex;
  getDataList();
};

const cancelEvent = () => {
  selectData.value = [];
};

// 新增数据
const insertOne = () => {
  addDataRef.value.open(null, "添加商品");
};

// 数据操作
const oper = (id, type) => {
  if (type == 1) {
    // 修改
    addDataRef.value.open(id, "修改商品");
    return;
  } else if (type === 2) {
    // 删除
    selectData.value = [id];
    batchDel();
  } else {
    // 上下架
    limitShop(id);
  }
};

// TODO  待改善
const handlerCommon = (item) => {
  let timer;
  setTimeout(() => {
    timer = setInterval(() => {
      if (isSend.value === 1) {
        item.imgUrl = imgUrl.value;
        save(item);
      } else {
        return;
      }
    }, 1000);
  }, 500);
  if (!isSend.value) {
    clearTimeout(timer);
  }
};

const save = (item) => {
  const formData = {
    id: item.id,
    desc: item.desc,
    discount: item.discount,
    imgUrl: item.imgUrl,
    marketable: item.marketable,
    title: item.title,
    price: item.price,
    sort: item.sort,
    type: item.type,
    date: item.date,
    dateUnit: item.dateUnit,
  };
  isSend.value = 2;
  request
    .post(`/shop/save`, formData)
    .then((res) => {
      if (res.code === 200) {
        ElMessage({
          message: "操作成功！",
          grouping: true,
          type: "success",
        });
        getDataList();
      }
      isSend.value = 0;
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const onUpload = (file) => {
  let formData = new FormData();
  if (file === null) {
    isSend.value = 1;
    return;
  }
  loading.value = true;
  formData.append("file", file);
  axios
    .post("https://zfb.bydhy.top/files/img", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      processData: false,
    })
    .then((res) => {
      if (res.data.code === 200) {
        imgUrl.value = res.data.data;
        isSend.value = 1;
      } else {
        ElMessage.error("图片上传失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const limitShop = (id) => {
  request
    .get(`/shop/limit?id=${id}`)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("操作成功");
        getDataList();
      } else {
        ElMessage.error("操作失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 批量删除
const batchDel = () => {
  request
    .post("/shop/del", selectData.value)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("网络错误");
    });
};

const onSubmit = () => {
  if (
    searchFrom.value.name == "" &&
    searchFrom.value.disocunt == null &&
    searchFrom.value.marketable == null
  ) {
    return;
  }
  getDataList();
};
const reset = () => {
  searchFrom.value = {
    name: "",
    discount: null,
    pageSize: 20,
    pageNum: 1,
    marketable: null,
  };
  getDataList();
};

// 多选
const handleSelectionChange = (val) => {
  let arr = val.map((item) => item.id);

  selectData.value = arr;
  if (selectData.value.length > 0) {
    isBatch.value = false;
  } else {
    isBatch.value = true;
  }
};

onMounted(() => {
  getDataList();
});
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-form {
  display: inline;
}
</style>
